package com.zjl.zweather.logic

import androidx.lifecycle.liveData
import com.zjl.zweather.logic.model.Place
import com.zjl.zweather.logic.network.ZWeatherNetWork
import kotlinx.coroutines.Dispatchers
import java.lang.Exception
import java.lang.RuntimeException

/**
 * Created by admin on 2020/12/1 .
 * With com.zjl.zweather.logic
 */
object Repository {

    //liveData函数可以自动构建并返回一个LiveData对象，然后再它的代码块中提供一个挂起函数的上下文，
    //这样我们就可以在liveData()函数的代码块中调用任意的挂起函数了
    fun searchPlaces(query: String) = liveData(Dispatchers.IO) {
        val result = try {
            val placeResponse = ZWeatherNetWork.searchPlaces(query)
            if (placeResponse.status == "ok") {
                val places = placeResponse.places
                Result.success(places)
            } else {
                Result.failure(RuntimeException("response status is ${placeResponse.status}"))
            }
        } catch (e: Exception) {
            Result.failure<List<Place>>(e)
        }
        emit(result as Result<List<Place>>)
    }

}